package persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

public class PoolConnection {
	private Vector<Connection> connections = new Vector<Connection>();
	protected String jdbc = "jdbc:mysql://";
	protected String servidor = "localhost/ainteractivas20141115";
	protected String usuario = "root";
	protected String password = "";
	protected int cantCon = 5;
	private static PoolConnection pool;

	private PoolConnection() {
		for (int i = 0; i < cantCon; i++)
			connections.add(connect());
	}

	public static PoolConnection getPoolConnection() {
		if (pool == null)
			pool = new PoolConnection();
		return pool;
	}

	private Connection connect() {
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");//"com.microsoft.sqlserver.jdbc.SQLServerDriver"
			String dbConnectString = jdbc + servidor;

			con = DriverManager.getConnection(dbConnectString,usuario, password);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return con;
	}

	public void closeConnections() throws SQLException {
		for (Connection connection : connections) {
			connection.close();
		}
	}

	public Connection getConnection() {
		Connection c = null;
		
		if (connections.isEmpty()) {
			c = connect();
			System.out.println("Se ha creado una nueva conexion fuera de los parametros de configuracion");
		} else {
			c = connections.remove(0);
		}
		
		return c;
	}

	public void releaseConnection(Connection c) {
		connections.add(c);
	}
}
